package tracking.service;

import java.sql.Connection;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import tracking.LTEConstants;
import tracking.LogUtil;
import tracking.Utils;
import tracking.dao.DBConnection;
import tracking.dao.Userdao;
import tracking.dto.BaseStatusDto;
import tracking.dto.Userdto;

@Path("/login")
public class LoginManager {
	private static final String TAG = "LoginManager";
	@GET
	@Path("/sign-in")
	@Produces("application/json")
	public String loginget(@QueryParam("data") String data) {
		if(data == null || data.isEmpty()){
			return userReturn(LTEConstants.STATUS_FAIL, "data is null");
		}
		
		try {
			Connection conn = DBConnection.getInstant().getConnection();
			if(conn == null){
				return userReturn(LTEConstants.STATUS_FAIL, "connection error");
			}
			LogUtil.log(TAG, "NECVN>>>" + TAG + "-" + "data:" + data);
			data = Utils.decode(data);
			Userdto user = Utils.getUserdtoFromJson(data);
			Userdao dao = new Userdao(conn);
			if(!dao.isCheckUSerOK(user)){
				return userReturn(LTEConstants.STATUS_FAIL, "User Incorrect");
			}
			return userReturn(LTEConstants.STATUS_OK, "Login success with user:" + user.getUserId());

		} catch (Exception e) {
			return userReturn(LTEConstants.STATUS_FAIL,"exception:" + e.toString());
			

		}

	}
	
	@GET
	@Path("/register")
	@Produces("application/json")
	public String registeer(@QueryParam("data") String data) {
		if(data == null || data.isEmpty()){
			return userReturn(LTEConstants.STATUS_FAIL, "data is null");
		}
		
		try {
			Connection conn = DBConnection.getInstant().getConnection();
			if(conn == null){
				return userReturn(LTEConstants.STATUS_FAIL, "connection error");
			}
			LogUtil.log(TAG, "NECVN>>>registeer" + TAG + "-" + "data:" + data);
			data = Utils.decode(data);
			Userdto dto = Utils.getUserdtoFromJson(data);
			Userdao dao = new Userdao(conn);
			if(dao.isUserIdExist(dto)){
				return userReturn(LTEConstants.STATUS_FAIL, "User is exist:" + dto.getUserId());
			}
			dao.insertUser(dto);
			return userReturn(LTEConstants.STATUS_OK, "register success with user:" + dto.getUserId());

		} catch (Exception e) {
			return userReturn(LTEConstants.STATUS_FAIL,"exception:" + e.toString());
			

		}

	}

	public String userReturn(int status, String message){
		BaseStatusDto dto = new BaseStatusDto();
		dto.setStatus(status);
		dto.setMessage(message);
		LogUtil.log(TAG, "userReturn:status" +status + ";message:" + message);
		return Utils.getString(dto);
	}
	
	
}
